package com.rytx.common.utils;

//import com.alipay.api.AlipayApiException;
//import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.rytx.common.config.MyAliPayConfig;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AilNotifyUtils {

    public static boolean rsaCheckV1(HttpServletRequest request, MyAliPayConfig myAliPayConfig, Logger logger){
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
            //boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
            //boolean flag = AlipaySignature.rsaCertCheckV1(params, myAliPayConfig.getAlipayPublicKey(), "UTF-8","RSA2");
//             千万不要调用错了！！！上面的才是证书验证调用的函数这个是普通验证调用函数
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, myAliPayConfig.getAlipayPublicKey(), myAliPayConfig.getCharset(), myAliPayConfig.getSignType());
            //验证成功返回true，失败返回false
            logger.info("支付宝异步通知验签结果：" + verifyResult);
            return verifyResult;
        }catch (AlipayApiException e) {
            logger.error("回调验签异常:{}",e);
            return false;
        }
    }
}
